package cn.dz.controller;

import cn.dz.entity.Employee;
import cn.dz.entity.User;
import cn.dz.service.UserService;
import cn.dz.utils.VerifyCodeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName UserController
 * @package: cn.dz.controller
 * @Description TODO
 * @Author dz
 * @Date 2024/12/22 17:06
 * @Version 1.0
 **/
@Controller
@RequestMapping("user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(DemoController.class);

    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 安全退出
     * @param session
     * @return
     */
    @RequestMapping("logout")
    public String logout(HttpSession session) {
        session.invalidate(); //session失效
        return "redirect:/employee/lists";
    }

    @RequestMapping("login")
    public String login(String username, String password, HttpSession session) {
        log.debug("本次登录用户名:{}", username);
        log.debug("本次登录密码:{}", password);
        try {
            //1.调用业务层进行登录
            User user = userService.login(username, password);
            //2.保存用户信息
            session.setAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/login"; //登录失败回到登录页面
        }
        return "redirect:/employee/lists";
    }

    /**
     * 用户注册
     * @return
     */
    @RequestMapping("/register")
    public String register(User user, String code, HttpSession session) {
        log.debug("用户名:{}, 真实姓名: {},密码: {}, 性别:{}", user.getUsername(), user.getRealname(), user.getPassword(), user.isGender());
        log.debug("用户输入验证码:{}", code);
        try {
            // 1. 判断用户输入验证码和session中验证码是否一致
            Object sessionCodeObject = session.getAttribute("code");

            // 检查 session 中是否有 "code" 属性
            if (sessionCodeObject == null) {
                throw new RuntimeException("验证码不存在或已过期");
            }

            String sessionCode = sessionCodeObject.toString();

            // 检查验证码是否一致（不区分大小写）
            if (!sessionCode.equalsIgnoreCase(code)) {
                throw new RuntimeException("验证码输入错误");
            }
            //2.注册用户
            String newPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
            user.setPassword(newPassword);
            userService.regist(user);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return "redirect:/regist"; // 注册失败，回到注册
        }
        return "redirect:/login"; // 注册成功回到登录
    }

    /**
     * 生成验证码
     */
    @RequestMapping("generateImageCode")
    public void generateImageCode(HttpSession session, HttpServletResponse response) throws IOException {
        // 1.生成4位随机数
        String code = VerifyCodeUtils.generateVerifyCode(4);
        // 2.保存到session作用域
        session.setAttribute("code", code);
        // 3.根据随机数生成图片 && 4.通过response响应图片 && 5.设置响应类型
        response.setContentType("image/png");
        log.debug("code:{}", session.getAttribute("code"));
        ServletOutputStream os = response.getOutputStream();
        VerifyCodeUtils.outputImage(200, 60, os, code);
    }

}
